package com.itheima.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器
 * 统一鉴权
 *
 * @author jjh
 * @date 2020/3/5
 **/
@Slf4j
//@Component
public class AuthGlobelFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 统一鉴权
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        // 认证失败
        if (!StringUtils.equals("admin", token)) {
            log.info("认证失败。。。");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 认证成功
        return chain.filter(exchange);
    }

    /**
     * 用来标志当前过滤器的优先级;值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
